import json


class IniTool:

    @classmethod
    def get_device_ini(cls, file_path):
        with open(file_path) as f:
            temp = f.readlines()
        head = temp[0].replace("\n", "")
        temp = temp[1:-1]
        new_temp = []
        for t in temp:
            new_temp.append(t.replace("\n", ""))
        data = {}
        for i in new_temp:
            item = i.split(":")
            try:
                value = int(item[1])
            except:
                value = item[1]
            data[str(int(item[0]))] = value
        data["head"] = head
        return data

    @classmethod
    def struct_json(cls, fresh_value, file_path):
        with open("../../ini_explain.json") as f:
            data = json.load(f)
        data_1 = data.get("data")[0]
        data_2 = data_1.get("controls")
        for name, value in fresh_value.items():
            for item in data_2:
                if item.get("name") == name:
                    item["value"] = value
        data_1["head"] = fresh_value["head"]
        with open(file_path, "w") as f:
            json.dump(data, f)

    @classmethod
    def change_json(cls, json_file_path, ini_file_path):
        with open(json_file_path) as f:
            data = json.load(f)
        data_1 = data.get("data")[0]
        head = data_1.get('head')
        data_2 = data_1.get("controls")
        with open(ini_file_path, "w") as f:
            f.write("{}\n".format(head))
            for item in data_2:
                if item.get("value") != "":
                    write_line = "{}:{}\n".format(IniTool.bu_wei(item.get("name")), item.get("value"))
                    f.write(write_line)
        crc = IniTool.getcrc("new.config", True)
        with open(ini_file_path, "a+") as f:
            f.write("crc:{}".format(crc))


    @classmethod
    def bu_wei(cls, name):
        if len(name) == 1:
            return "00{}".format(name)
        elif len(name) == 2:
            return "0{}".format(name)
        else:
            return name

    @classmethod
    def getcrc(cls, file, invert):
        with open(file, 'rb') as f:
            contents = f.read()
        a = 0xFFFF
        b = 0xA001
        for byte in contents:
            try:
                a ^= byte
            except Exception as e:
                raise e
            for i in range(8):
                last = a % 2
                a >>= 1
                if last == 1:
                    a ^= b
        s = hex(a).upper()
        if invert == True:
            result = s[4:6] + s[2:4]
        else:
            result = s[2:4] + s[4:6]
        return result


if __name__ == '__main__':
    file_path = "tac.config"
    v = IniTool.get_device_ini(file_path)
    IniTool.struct_json(v, "new.json")
    IniTool.change_json("new.json", "new.config")
